const express = require('express');
const bodyParser = require('body-parser');
const userModel = require("./models")
const app = express();

const static = express.static;
app.use(static("./static"));

// 解析表单数据
app.use(bodyParser.json());

// 留言列表回复功能
// const messages = [];

app.get('/', (req, res)=> {
    res.sendFile(__dirname + "/views/index.html")
});

// 返回留言列表
app.get('/api/messages', async (req, res)=> {
  let datas = await userModel.find();
  res.json(datas);
});

// 添加留言
app.post('/api/messages', async (req, res)=> {
  let obj = {
    username: req.body.username,
    message: req.body.message
  }
  await userModel.create(obj);
  res.json({
    info: "添加成功",
    status: 1
  });
});

// 删除留言
app.delete('/api/messages', async (req, res)=> {
  await userModel.deleteOne(req.params._id);
  res.json({
    info: "删除成功",
    status: 1
  });
});

// 新增回复
app.post('/api/replies', async (req, res)=> {
  let {val,id} = {
    val: req.body.val,
    id: req.body.id
  }
  let strArr = [val];
  let [datas] = await userModel.find({_id:id});
  if (datas.replies) {
    datas.replies = datas.replies.concat(strArr);
  }else{
    datas.replies = strArr;
  }
  await userModel.updateOne({_id:id},{$set:{replies:datas.replies}})
  res.json({
    info: "添加成功",
    status: 1
  });
});

// 启动服务器
app.listen(3000);